#!/usr/bin/env python
# -*- coding: utf-8 -*-
import random
from flask import current_app
from redis.exceptions import RedisError
from common.utils.mailer import send_email


def generate_code(length=6):
    """生成随机验证码"""
    return ''.join(random.choices('0123456789', k=length))


def send_email_code(redis_client, email, purpose="reset"):
    """
    发送邮箱验证码
    :param redis_client: Redis 客户端
    :param email: 收件人邮箱
    :param purpose: 验证用途，如 register/login/reset
    """
    code_key = f"email:code:{purpose}:{email}"
    cooldown_key = f"email:cooldown:{purpose}:{email}"

    try:
        if redis_client.get(cooldown_key):
            return {"success": False, "msg": "验证码发送太频繁，请稍后再试~"}

        code = generate_code()
        redis_client.set(name=code_key, value=code, time=300)         # 5分钟有效
        redis_client.set(name=cooldown_key, value=1, time=60)         # 1分钟冷却
        current_app.logger.info(f"{email} 验证码：{code}")

        # 构造邮件内容
        subject = "【账单笔记】您的验证码"
        body = f"您好，您的验证码是：{code}，有效期5分钟。请勿泄露。如非本人操作请忽略此邮件。"

        # 发送邮件
        if send_email(email, subject, body):
            return {"success": True, "msg": "验证码已发送，请查收邮箱"}
        else:
            return {"success": False, "msg": "邮件发送失败，请稍后重试"}

    except RedisError as e:
        current_app.logger.error(f"Redis 写入验证码失败：{e}")
        return {"success": False, "msg": "系统繁忙，请稍后再试"}
